package com.infisight.hudprojector.service;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.google.gson.Gson;
import com.infisight.hudprojector.common.HudProjectApplication;
import com.infisight.hudprojector.data.AppControlActionClass;
import com.infisight.hudprojector.data.DataMoreLevelClass;
import com.infisight.hudprojector.data.DataTextMessageClass;
import com.infisight.hudprojector.data.PMessage;
import com.infisight.hudprojector.util.Constants;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

/**
 * 消息接收中心，依据接收的消息发送到相应的界面，现阶段采用单向的输出模式，以后再考虑加入双向的Socket通讯模式
 * 
 * @author Administrator
 * 
 */
public class MsgServer implements Runnable {
	String TAG = "MsgServer";
	public static final int SERVERPORT = 8988;
	Context mContext;
	ServerSocket serverSocket = null;
	Socket socket;
	static Vector usrList = new Vector(1, 1);

	public MsgServer(Context context) {
		mContext = context;
		try {
			serverSocket = new ServerSocket(SERVERPORT);
		} catch (IOException ioe) {
			System.out.println("Can't set up server socket." + ioe);
		}
		System.out.println("server start ...");
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (true) {
				Log.i(TAG, "正在等待连接.....");
				socket = serverSocket.accept();
				Log.i(TAG, "已连接.....");
				usrThread ut = new usrThread(socket, mContext);
				new Thread(ut).start();
				usrList.addElement(ut);
				Log.d("TAG", "createGroup:onSuccess");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

class usrThread implements Runnable {
	Socket socket;
	Context mContext;
	ObjectInputStream osFromClient;
	ObjectOutputStream osToClient;
	// thPut tp;
	// thGet tg;
	// static int msgCount = 0;
	// static Vector msgBox = new Vector(1, 1);// 动态数组
	List<PMessage> msgLsts = new ArrayList<PMessage>();
	// int localCount = 0;
	ExecutorService cachedThreadPool;
	SharedPreferences sp;

	// 读取消息，发送给手机端
	public synchronized void writeMsg(PMessage msg) {
		// 在这里实现对消息的接收
		// msgBox.addElement(msg);
		msgLsts.add(msg);
		// msgCount++;
		Log.d("usrThread", "writeMsg(PMessage msg)");
	}

	// 写入消息，接收手机端信息
	public synchronized PMessage readMsg() {
		// PMessage msg = (PMessage) (msgBox.elementAt(localCount));// 放到这里面
		PMessage msg = msgLsts.get(0);
		// localCount++;
		return msg;
	}

	// 写入消息
	public synchronized void readMsg(PMessage pm) {
		Gson gson = new Gson();
		int cmd = pm.command;
		switch (cmd) {
		case Constants.TYPE_AUDIO:
			break;
		case Constants.TYPE_CMD:
			try {
				String content = pm.message;
				Log.d("readMsg", content);
				DataTextMessageClass dtmc = gson.fromJson(content,
						DataTextMessageClass.class);
				ProcessBroadcast(dtmc.getCmd(), dtmc.getContent());
			} catch (Exception e) {
				Log.d("usrThread", "e.Message:" + e.getMessage());
			}
			break;
		case Constants.TYPE_IMG:
			break;
		case Constants.TYPE_STREAM:
			break;
		case Constants.TYPE_TEXT:
			try {
				String content = pm.message;
				Log.d("usrThread", content);
				DataTextMessageClass dtmc = gson.fromJson(content,
						DataTextMessageClass.class);
				Log.d("usrThread", dtmc.getContent() + "-=" + dtmc.getCmd());
				if (content != "心跳处理") {
					ProcessBroadcast(dtmc.getCmd(), dtmc.getContent());
				}

			} catch (Exception e) {
				Log.d("usrThread", "e.Message:" + e.getMessage());
			}
			break;
		case Constants.TYPE_RETURNIFO:
			try {
				String content = pm.message;
				DataTextMessageClass dtmc = gson.fromJson(content,
						DataTextMessageClass.class);
				if (dtmc.getCmd().equals(Constants.RETURNWIFIDIRECTSTATE)) {// 判断wifi-direct是否连接上
					// Log.d("MsgServer", "e.Message:------里面");
					// PMessage pm2 = new PMessage();
					// pm2.message = Constants.WIFIDIRECTSTATE;
					// writeMsg(pm2);
					ProcessBroadcast(dtmc.getCmd(), null);
				}
			} catch (Exception e) {
				Log.d("usrThread", "e.Message:" + e.getMessage());
			}
			break;
		}

	}

	public usrThread(Socket s, Context mcontext) {
		// 在这个里面注册，有了新消息之后，就将新消息放到队列中去，然后使用线程去读取
		sp = mcontext.getSharedPreferences("AppControlDevice",
				Activity.MODE_PRIVATE);
		socket = s;
		mContext = mcontext;
		cachedThreadPool = Executors.newCachedThreadPool();
		try {
			Log.d("TAG", "mNewMsgReceiver   usrThread");
			osToClient = new ObjectOutputStream(socket.getOutputStream());
			osFromClient = new ObjectInputStream(new BufferedInputStream(
					socket.getInputStream()));
			mContext.registerReceiver(mMobileMsgReceiver,
					makeNewMsgIntentFilter());
			// 读取客户端消息
			new Thread(new Runnable() {
				PMessage msg;
				Gson gson = new Gson();

				public void run() {
					while (true) {
						try {
							// Object obj = osFromClient.readObject();
							// msg = (PMessage) obj;
							String str = (String) osFromClient.readObject();
							msg = gson.fromJson(str, PMessage.class);
							readMsg(msg);
						} catch (Exception e) {
						}
					}
				}
			}).start();
			// 发送HUD消息到客户端
			new Thread(new Runnable() {
				// PMessage msg;
				Gson gson = new Gson();

				public void run() {
					try {
						while (true) {

							// if (localCount < msgCount) {
							// msg = readMsg();
							if (msgLsts.size() != 0) {
								if (sp.getString("deviceid", null) != null) {
									String str = gson.toJson(readMsg());
									Log.d("TAG", str + "--发送hud消息");
									osToClient.writeObject(str);
									osToClient.flush();
									osToClient.reset();
									msgLsts.clear();
									// Log.i("TAG", msgCount + "--" +
									// localCount);
								}
							}
							// }

						}
					} catch (Exception e) {
						System.out.println("Receive error" + e.getMessage());
					}
				}
			}).start();
			// tp = new thPut();
			// tp.start();
			// tg = new thGet();
			// tg.start();
		} catch (Exception e) {
			System.out.println("usrThread init error! " + e);
		}
	}

	// // 读取客户端消息
	// class thPut extends Thread {
	// PMessage msg;
	//
	// public void run() {
	// try {
	// while (true) {
	// try {
	// Object obj = osFromClient.readObject();
	// msg = (PMessage) obj;
	// readMsg(msg);
	// } catch (Exception e) {
	// }
	// }
	// } catch (Exception e) {
	// System.out.println("Receive error" + e.getMessage());
	// }
	// }
	// }
	//
	// // 发送HUD消息到客户端
	// class thGet extends Thread {
	// // Declare the currnet message get from readMsg method
	// PMessage msg = null;
	//
	// public void run() {
	// try {
	// while (true) {
	//
	// if (localCount < msgCount) {
	// msg = readMsg();
	// osToClient.writeObject(msg);
	// osToClient.flush();
	// osToClient.reset();
	// localCount++;
	// }
	//
	// }
	//
	// } catch (Exception e) {
	// System.out.println("cant write msg to client" + e);
	//
	// }
	// }
	//
	// }

	/**
	 * 新消息过滤器
	 * 
	 * @return
	 */
	private IntentFilter makeNewMsgIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.MSG_SEND);
		intentFilter.addAction(Constants.AppControlAuthorityAction);
		return intentFilter;
	}

	/**
	 * 广播接收器,这个应该是SendMsg
	 */
	public BroadcastReceiver mMobileMsgReceiver = new BroadcastReceiver() {
		SharedPreferences sp;

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			sp = context.getSharedPreferences("AppControlDevice",
					Activity.MODE_PRIVATE);
			try {
				final String action = intent.getAction();
				if (action != null && Constants.MSG_SEND.equals(action)) {
					String strnmsg = intent.getStringExtra("NMESSAGE");
					Log.d("TAG", "strnmsg--------------" + strnmsg);
					if (!strnmsg.equals("")) {
						PMessage nmsg = gson.fromJson(strnmsg, PMessage.class);
						writeMsg(nmsg);
						Log.d("TAG", "数据已经发送到Mobile");
					}

				}
				// 主从设备控制代码
				else if (action != null
						&& Constants.AppControlAuthorityAction.equals(action)) {

					String strnmsg = intent.getStringExtra(Constants.MSG_PARAM);
					if (strnmsg != null) {
						AppControlActionClass acac = gson.fromJson(strnmsg,
								AppControlActionClass.class);
						sp.edit().putString("deviceid", acac.DeviceId).commit();
						Log.i("TAG", "主设备的id：" + acac.DeviceId + "主设备的name:"
								+ acac.DeviceName);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	/**
	 * 将新消息广播出去
	 */
	private void ProcessBroadcast(String newCmd, String newMsg) {
		String stringIntentAction = newCmd;
		Intent intentAction = new Intent(stringIntentAction);
		intentAction.putExtra(Constants.MSG_CMD, newCmd);
		intentAction.putExtra(Constants.MSG_PARAM, newMsg);
		mContext.sendBroadcast(intentAction);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}
}
